<template>
  <div class="single-container">
    <search-form
      :config-list="searchFormConfig"
      @search="search"
      @reset="reset"
      ref="searchFormRef"
      @datetimerange="dateRange"
    >
      <template #leftSlot>
        <!--左侧的插槽-->
        <el-button
          icon="Search"
          type="primary"
          @click="exportData"
          v-permissions="['exportSalesOrder']"
        >
          导出订单
        </el-button>
        <el-button
          icon="Search"
          type="primary"
          @click="printSingleCreate"
          v-permissions="['printSalesOrder']"
        >
          打印
        </el-button>
        <el-button
          icon="Edit"
          type="primary"
          @click="batchSettlement"
          v-permissions="['batchSettlementSupplier']"
        >
          批量结款
        </el-button>
      </template>
      <template #rightSlot>
        <!--右侧的插槽-->
      </template>
    </search-form>
    <CustomTable
      :pagination="pagination"
      :table-config="tableConfig"
      @pagination-change="paginationChange"
      @actions-click="actionsClick"
      @change="change"
      @selectionChange="selectionChange"
    >
      <template #user_name="{ row }">
        <div class="user-info">
          <div class="user-info-item">
            <span class="user-info-item-label">名称：</span>
            <span class="user-info-item-value">{{ row.user_name }}</span>
          </div>
          <div class="user-info-item">
            <span class="user-info-item-label">电话：</span>
            <span class="user-info-item-value">{{ row.user_mobile }}</span>
          </div>
        </div>
      </template>
      <template #consignee="{ row }">
        <div class="user-info">
          <div class="user-info-item">
            <span class="user-info-item-label">收货人：</span>
            <span class="user-info-item-value">{{ row.consignee }}</span>
          </div>
          <div class="user-info-item">
            <span class="user-info-item-label">电话：</span>
            <span class="user-info-item-value">{{ row.consignee_mobile }}</span>
          </div>
          <div class="user-info-item">
            <span class="user-info-item-label">地址：</span>
            <span class="user-info-item-value">{{ row.address }}</span>
          </div>
        </div>
      </template>

      <template #singleSalespayment="{ row }">
        <el-button
          v-if="
            [2, 3, 4].includes(row.order_status) &&
            row.settle_payment_status !== 2
          "
          v-permissions="['singleSalespayment']"
          text="结款"
          type="primary"
          @click="paymentClick(row)"
        >
          结款
        </el-button>
      </template>
    </CustomTable>
    <sendSingle ref="sendSingleRef" @fetch-data="queryProject" />
  </div>
</template>

<script>
  export default {
    name: 'singleSales',
  }
</script>

<script setup>
  import CustomTable from '@/views/component/CustomTable'
  import SearchForm from '@/views/component/SearchForm' //引入搜索组件
  import {
    getSingleStoreList as getList,
    paymentSingleSales,
  } from '@/api/single'
  import { useRouter } from 'vue-router'
  import { exportSet } from '@/utils/export'
  import sendSingle from './conponents/sendSingle.vue'
  import { printSingle, printSingleDOM } from '@/utils/print'
  import { message } from '@/utils/helper'
  const router = useRouter()

  // 搜索参数
  const queryForm = ref({})

  const tableConfig = reactive({
    isSelect: true,
    columns: [
      {
        label: 'ID',
        prop: 'id',
        sortable: false,
        width: 80,
        fixed: 'left',
      },
      { label: '订单号', prop: 'order_sn', sortable: false, width: 120 },
      {
        label: '买家信息',
        prop: 'user_name',
        sortable: false,
        width: 220,
        slotName: 'user_name',
      },
      {
        label: '收货信息',
        prop: 'consignee',
        sortable: false,
        width: 320,
        slotName: 'consignee',
      },
      // {
      //   label: '支付状态',
      //   prop: 'order_status',
      //   sortable: false,
      //   width: 120,
      //   customType: 'ElTag',
      //   tagKeyValue: 'payStatusTag',
      // },
      {
        label: '结款状态',
        prop: 'settle_payment_status',
        sortable: false,
        width: 110,
        customType: 'ElTag',
        tagKeyValue: 'settle_payment_statusTag',
      },
      {
        label: '订单状态',
        prop: 'order_status',
        sortable: false,
        width: 110,
        customType: 'ElTag',
        tagKeyValue: 'statusTag',
      },
      {
        label: '订单金额',
        prop: 'pay_amount',
        sortable: false,
        width: 120,
        showOverflowTooltip: true,
      },
      { label: '创建时间', prop: 'create_time', sortable: false, width: 180 },
      {
        label: '操作',
        action: true,
        fixed: 'right',
        actions: [
          {
            fnName: 'payment',
            title: '结款',
            type: 'primary',
            isTextBtn: true,
            slotBtnName: 'singleSalespayment',
            permissionCode: 'singleSalespayment', // 权限
          },
          {
            fnName: 'view',
            title: '查看',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'singleSalesView', // 权限
          },
          {
            fnName: 'send',
            title: '发货',
            type: 'primary',
            isTextBtn: true,
            permissionCode: 'singleSalesSend', // 权限
            key: 'order_status',
            showValue: 2,
          },
        ],
      },
    ],
    tagConfig: {
      payStatusTag: {
        1: {
          name: '未付款',
          type: 'info',
        },
        2: {
          name: '已付款',
          type: 'primary',
        },
      },
      //审批状态 1:审批中 2:审批通过 3:审核不通过
      statusTag: {
        1: {
          name: '待确认',
          type: 'info',
        },
        2: {
          name: '待发货',
          type: 'primary',
        },
        3: {
          name: '待收货',
          type: 'warning',
        },
        4: {
          name: '已完成',
          type: 'success',
        },
        // 5: {
        //   name: '交易关闭',
        //   type: 'danger',
        // },
        // 6: {
        //   name: '售后中',
        //   type: 'warning',
        // },
        7: {
          name: '订单取消',
          type: 'danger',
        },
      },
      settle_payment_statusTag: {
        1: {
          name: '未结款',
          type: 'warning',
        },
        2: {
          name: '已结款',
          type: 'primary',
        },
        3: {
          name: '已退款',
          type: 'danger',
        },
      },
    },
    list: [],
    listLoading: false,
  })

  //搜索组件配置信息
  const searchFormConfig = reactive({
    config: {
      layoutType: 1, //1:左右布局,2:上下布局
      leftPanelWidth: 0, //控制左边布局控件宽度
    },
    controlList: [
      { label: '订单号', prop: 'order_sn', type: 'input' },
      { label: '买家信息', prop: 'buyer_info', type: 'input' },
      {
        label: '收货人',
        prop: 'consignee',
        type: 'input',
      },
      {
        label: '创建时间',
        prop: 'create_time',
        type: 'datetimerange',
        start: 'create_time_start',
        end: 'create_time_end',
      },

      {
        label: '结款状态',
        prop: 'settle_payment_status',
        type: 'select',
        list: Object.keys(
          tableConfig['tagConfig']['settle_payment_statusTag']
        ).reduce((acc, cur) => {
          const { name } =
            tableConfig['tagConfig']['settle_payment_statusTag'][cur]
          acc.push({ label: name, value: cur })
          return acc
        }, []),
      },
      {
        label: '订单状态',
        prop: 'order_status',
        type: 'select',
        list: Object.keys(tableConfig['tagConfig']['statusTag']).reduce(
          (acc, cur) => {
            const { name } = tableConfig['tagConfig']['statusTag'][cur]
            acc.push({ label: name, value: cur })
            return acc
          },
          []
        ),
      },
    ],
  })

  //点击搜索触发
  const search = (form) => {
    console.log(form)
    pagination.page = 1
    queryForm.value = form
    queryProject()
  }

  //列表分页参数
  const pagination = reactive({
    page: 1, //每页条数
    limit: 10, //当前页
    total: 0,
    layout: 'total, sizes, prev, pager, next, jumper',
  })

  //分页控件点击操作
  const paginationChange = (data) => {
    const { val, type } = data
    pagination[type] = val
    queryProject()
  }

  //请求列表数据
  const queryProject = () => {
    tableConfig.listLoading = true
    getList({
      ...queryForm.value,
      limit: pagination.limit,
      page: pagination.page,
    })
      .then((result) => {
        console.log('result', result)
        tableConfig.list = result.data.data
        tableConfig.listLoading = false
        pagination.total = result.data.total
      })
      .catch(() => {
        tableConfig.listLoading = false
      })
  }
  const sendSingleRef = ref(null)
  //点击表格操作按钮回调
  const actionsClick = (data) => {
    console.log('actionsClick===', data)
    const { type, row } = data
    switch (type) {
      case 'view':
        router.push({
          path: '/single/singleSalesInfo',
          query: {
            id: row.id,
          },
        })
        break
      case 'send':
        sendSingleRef.value.open(row)
        break
    }
  }
  const paymentClick = (row) => {
    ElMessageBox.confirm(
      '您确定已经收到货款了?点击确定订单状态将变为已结款',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      await paymentSingleSales({ id: row.id })
      message('结款成功')
      queryProject()
    })
  }

  const searchFormRef = ref(null)
  const reset = () => {
    if (!searchFormRef.value) return
    searchFormRef.value.resetFormFields()
    queryProject()
  }

  const init = async () => {
    await queryProject()
  }
  const selectList = ref([])
  const selectionChange = (data) => {
    selectList.value = data
  }

  const dateRange = (event) => {
    if (event) {
      queryForm.value.create_time_start = event[0]
      queryForm.value.create_time_end = event[1]
    } else {
      queryForm.value.create_time_start = ''
      queryForm.value.create_time_end = ''
    }
  }

  const exportData = () => {
    if (selectList.value.length === 0) {
      message('请选择要导出的订单', 'warning')
      return
    }
    exportSet(
      selectList.value.map((item) => item.id),
      '销售单导出'
    )
  }

  const printSingleCreate = () => {
    printSingleDOM(selectList.value, '销售送货单')
  }

  const batchSettlement = async () => {
    if (selectList.value.length === 0) {
      message('请选择要结款的订单', 'warning')
      return
    }
    const arrs = selectList.value.filter(
      (item) =>
        [2, 3, 4].includes(item.order_status) &&
        item.settle_payment_status !== 2
    )
    if (arrs.length === 0)
      return message('您选择的订单均不符合结款条件', 'warning')
    const totalAmount = arrs.reduce(
      (pre, cur) => Number(pre) + Number(cur.pay_amount),
      0
    )
    ElMessageBox.confirm(
      `已过滤已结款以及不符合结款状态的订单，确认要结款当前<span style="color: red; font-weight: bold;">${arrs.length}</span>个订单，总金额<span style="color: red; font-weight: bold;">${totalAmount}</span>元吗？`,
      '提示',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const id = arrs.map((item) => item.id).join(',')
      await paymentSingleSales({ id })
      message('结款成功')
      queryProject()
    })
  }

  onMounted(() => {
    init()
  })
</script>

<style lang="scss" scoped>
  .user-info {
    display: flex;
    flex-direction: column;
  }
  .user-info-item {
    display: flex;
    margin-left: 30px;
    .user-info-item-label {
      text-align: right;
    }
    .user-info-item-value {
      flex: 1;
      text-align: start;
    }
  }
</style>
